package com.example.administrator.liveapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.TimeChangeUtil;
import com.github.yoojia.qrcode.qrcode.QRCodeEncoder;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 活动请假（门票）activity
 */

public class CancellationPage extends AppCompatActivity {

    private ImageView Qr_code;
    private Button ask_leave_button;//请假
    private Button cancel_button;//取消预约
    private Bitmap qrCodeImage;
    private TextView name;
    private TextView times;
    private String activityId;//活动Id
    private String consumerId;//用户Id
    private TextView place;
    private String time, endtime;
    private String address;
    private String consumerName;
    private String ImageUrl;
    private ImageView invitation_image;
    private String NeedPay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cancellation_page);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        initView();
        qrCodeImageView();
    }

    private void initView() {
        Intent intent = getIntent();
        consumerId = intent.getStringExtra("consumerId");
        activityId = intent.getStringExtra("activityId");
        time = intent.getStringExtra("time");//请假结束时间
        endtime = TimeChangeUtil.getStrTime(intent.getStringExtra("endtime"));
        NeedPay = intent.getStringExtra("NeedPay");
        address = intent.getStringExtra("address");
        consumerName = intent.getStringExtra("consumerName");
        ImageUrl = intent.getStringExtra("ImageUrl");
        Qr_code = (ImageView) findViewById(R.id.Qr_code);
        cancel_button = (Button) findViewById(R.id.cancel_button);
        invitation_image = (ImageView) findViewById(R.id.invitation_image);
        name = (TextView) findViewById(R.id.consumerName);
        place = (TextView) findViewById(R.id.address);
        times = (TextView) findViewById(R.id.time);
        name.setText("\"" + consumerName + "\"");
        place.setText(address);
        times.setText(endtime);
        Glide.with(this).load(AppUrl.URL+ImageUrl).into(invitation_image);
    }

    private void qrCodeImageView() {
        // 二维码中间图标
        final Bitmap centerImage = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        // 生成的二维码图案
        qrCodeImage = new QRCodeEncoder.Builder()
                .width(180) // 二维码图案的宽度
                .height(180)
                .paddingPx(0) // 二维码的内边距
                .marginPt(0) // 二维码的外边距
//                .centerImage(centerImage) // 二维码中间图标
                .build()
                .encode(AppUrl.URLS + AppUrl.SignInURL + "?activityId=" + activityId + "&consumerId=" + consumerId + "&type=1");
        Qr_code.setImageBitmap(qrCodeImage);

        cancel_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                String str = sdf.format(new java.util.Date());
                long times = Long.parseLong(TimeChangeUtil.getTimeStamp(str));//系统当前时间戳
                long stoptime = (times - Long.parseLong(time))*1000;
                if (stoptime <= 0) {
                    if(NeedPay.equals("0")){
                        String url = AppUrl.URLS + AppUrl.CancelReservation;
                        Map<String, String> map = new HashMap<>();
                        map.put("consumerId", consumerId);
                        map.put("activityId", activityId);
                        map.put("statics", "2");
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("6006")) {
                                    Toast.makeText(CancellationPage.this, "已请假", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent();
                                    intent.putExtra("consumerId", consumerId);
                                    intent.setClass(CancellationPage.this, MyReservationPage.class);
                                    startActivity(intent);
                                    overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                    finish();
                                } else if (code.equals("6008")) {
                                    Toast.makeText(CancellationPage.this, "没有查找到相关活动", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                            }
                        });
                    }else if(NeedPay.equals("1")){
                        String url = AppUrl.URLS + AppUrl.refunds;
                        Map<String, String> map = new HashMap<>();
                        map.put("consumerId", consumerId);
                        map.put("activityId", activityId);
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("result");
                                if (code.equals("success")) {
                                    Toast.makeText(CancellationPage.this, "已退款", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent();
                                    intent.putExtra("consumerId", consumerId);
                                    intent.setClass(CancellationPage.this, MyReservationPage.class);
                                    startActivity(intent);
                                    overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                    finish();
                                }else{
                                    Toast.makeText(CancellationPage.this, "退款失败", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(CancellationPage.this, ex.getMessage()+"", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } else {
                    Toast.makeText(CancellationPage.this, "请假时间已过,无法请假", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}
